<?php

namespace app\api\controller;

use think\Controller;
use think\facade\Request;

class Login extends Controller
{
    protected $user_model;

    public function __construct()
    {
        parent::__construct();
        $this->user_model   = new \app\common\model\User();
    }

    /**
     * 获取微信用户信息
     */
    public function getWxUserInfo()
    {
        // 获取微信配置
        $appid = config('wx.app_id');
        $secret = config('wx.secret');
        // 获取code
        $code = input('code');
        if (empty($code)) {
            return json(['code' => 100, 'msg' => '缺少code参数']);
        }
        // 通过code获取access_token
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
        // 使用file_get_contents发起HTTP GET请求
        $result = file_get_contents($url);
        $result = json_decode($result, true);
        if (!isset($result['openid'])) {
            return json(['code' => 101, 'msg' => '获取access_token失败：' . $result['errmsg']]);
        }
        // 获取用户信息
        $access_token = $result['access_token'];
        $openid = $result['openid'];
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $userinfo = curl_exec($ch);
        curl_close($ch);
        $userinfo = json_decode($userinfo, true);
        if (isset($userinfo['errcode'])) {
            return json(['code' => 102, 'msg' => '获取用户信息失败：' . $userinfo['errmsg']]);
        }
        // 通过openid查询用户是否存在
        $user = $this->user_model->getOne(['openid' => $openid], 'token', 'id ASC');
        if ($user) {
            // 用户存在，返回用户ID
            $token = $user['token'];
        } else {
            // 用户不存在，创建新用户
            $token = Request::token();
            $userData = [
                'openid' => $openid,
                'nick_name' => $userinfo['nickname'],
                'headimgurl' => $userinfo['headimgurl'],
                'sex' => $userinfo['sex'],
                'province' => $userinfo['province'],
                'city' => $userinfo['city'],
                'country' => $userinfo['country'],
                'create_time' => time(),
                'update_time' => time(),
                'token' => $token
            ];
            try {
                // 插入用户数据
                $userId = $this->user_model->addData($userData);
                if (!$userId) {
                    return json(['code' => 104, 'msg' => '创建用户失败']);
                }
            } catch (\Exception $e) {
                return json(['code' => 103, 'msg' => '创建用户失败：' . $e->getMessage()]);
            }
        }
        $link = 'https://api.qiming.com/v1/index.html?token=' . $token;
        $this->redirect($link);
    }

    /**
     * 跳转地址
     */
    public function index()
    {
        // 获取微信配置
        $appid = config('wx.app_id');
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' .
            'appid=' . $appid .
            '&redirect_uri=' . urlencode('https://api.qiming.com/v1/get_user_info') .
            '&response_type=code' .
            '&scope=snsapi_userinfo' .
            '&state=' . rand(1000, 9999) . '#wechat_redirect';
        $this->redirect($url);
    }
}
